package ar.edu.unq.wannaplay.panels;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;

public abstract class AbstractBasicEditPanel<M, S> extends ServicedPanel<S> {

    private static final long serialVersionUID = 1L;

    private M modelObject;

    private Form<?> form;

    private final FeedBackPanel feedBackPanel;

    public AbstractBasicEditPanel(final String id, final M modelObject, final S service,
            final FeedBackPanel feedBackPanel) {
        super(id, service);
        this.modelObject = modelObject;
        this.feedBackPanel = feedBackPanel;
        this.initialize();
    }

    private void initialize() {

        this.setForm(this.createForm("form"));
        this.addFields(this.getForm(), this.getFieldsStrings());
        this.add(this.getForm());
        this.addComponents();

    }

    protected abstract String[] getFieldsStrings();

    protected abstract void addComponents();

    protected abstract void acceptAction();

    protected void addFields(final Form<?> aForm, final String[] fieldsNames) {
        for (String field : fieldsNames) {
            aForm.add(this.createTextField(field));
        }
    }

    @SuppressWarnings("rawtypes")
    private TextField createTextField(final String field) {
        return new TextField(field);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected Form<?> createForm(final String id) {
        Form aForm = new Form(id, new CompoundPropertyModel(this.getModelObject()));
        AjaxButton ajax = new AjaxButton("accept") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(final AjaxRequestTarget target, final Form<?> anotherForm) {
                AbstractBasicEditPanel.this.acceptAction();
                target.addComponent(AbstractBasicEditPanel.this.getFeedBackPanel());
            }
        };
        aForm.add(ajax);
        return aForm;
    }

    public M getModelObject() {
        return modelObject;
    }

    public void setModelObject(final M modelObject) {
        this.modelObject = modelObject;
    }

    protected Form<?> getForm() {
        return form;
    }

    public void setForm(final Form<?> form) {
        this.form = form;
    }

    public FeedBackPanel getFeedBackPanel() {
        return feedBackPanel;
    }

}
